import { Card as SemiCard, ButtonGroup, Button, List } from "@douyinfe/semi-ui";
import { IconRefresh, IconDelete, IconPlusCircle, IconEdit } from "@douyinfe/semi-icons";
import { useEffect } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { Row, Col, Popconfirm, Space, Descriptions, Table, message, Tooltip } from "antd";
import { EyeOutlined, ApartmentOutlined, TableOutlined } from "@ant-design/icons";

import useHelperInstitution from "../helper/useHelperInstitution";

import useAllInstitutions from "../hooks/institution/useAllInstitutions";
import useDeleteInstitution from "../hooks/institution/useDeleteInstitution";
import useInstitutionMembers from "../hooks/institution/useInstitutionMembers";
import useInstitutionDepartmentsWithMembers from "../hooks/institution/useInstitutionDepartmentsWithMembers";
import useInstitutionDeletePosition from "../hooks/institution/useDeletePosition";

const oiType = "项目组";

const ProjectPage = () => {
    const { windowInnerHeight } = useModel("global");
    const { openAddProjectInstitutionModal } = useHelperInstitution();

    const { loading, institutions, loadAllInstitutions } = useAllInstitutions(oiType);

    const state = useReactive({
        currentProject: {},
        currentOperate: oiType + "详情",
        showType: "table",
    });

    useEffect(() => {
        let currentProject = institutions.find((item) => item.oiUuid === state.currentProject?.oiUuid);
        !currentProject && institutions.length > 0 && (currentProject = institutions[0]);
        state.currentProject = currentProject || {};
    }, [institutions]);

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={5}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{oiType}列表</span>}
                        headerStyle={{ padding: "7px 12px" }}
                        headerExtraContent={
                            <ButtonGroup>
                                <Button icon={<IconPlusCircle />} onClick={() => openAddProjectInstitutionModal({ oiType, reloadData: loadAllInstitutions })}></Button>
                                <Button icon={<IconRefresh />} onClick={loadAllInstitutions}></Button>
                            </ButtonGroup>
                        }
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto", textAlign: "center" }}
                    >
                        <List
                            loading={loading}
                            dataSource={institutions}
                            renderItem={(item) => (
                                <List.Item
                                    className={`list-item ${state.currentProject?.oiUuid === item?.oiUuid ? "list-item-selected" : ""}`}
                                    style={{ padding: "12px 12px 12px 24px" }}
                                    main={item?.oiName}
                                    onClick={() => (state.currentProject = item)}
                                ></List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={19}>{state.currentProject?.oiUuid && <ProjectDetail {...state} currentProject={state.currentProject} reloadData={loadAllInstitutions} />}</Col>
            </Row>
        </div>
    );
};

const ProjectDetail = ({ currentProject, showType, currentOperate, reloadData }) => {
    const { windowInnerHeight } = useModel("global");
    const { openEditProjectInstitutionModal, openAddInstitutionMemberModal, openAddProjectInstitutionDepartmentModal } = useHelperInstitution();
    const { loading, loadInstitutionMembers, members } = useInstitutionMembers(currentProject.oiUuid);
    const { loading: dpLoading, loadInstitutionDepartmentsWithMembers, departments } = useInstitutionDepartmentsWithMembers(currentProject.oiUuid, "职能部门");
    const { deleteInstitution } = useDeleteInstitution();

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <Row gutter={10}>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{currentOperate}</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 10, height: cardBodyHeight }}
                    headerExtraContent={
                        <Space>
                            <ButtonGroup className="bnts">
                                <Button
                                    title="编辑当前项目组信息"
                                    icon={<IconEdit />}
                                    onClick={() => openEditProjectInstitutionModal({ institution: currentProject, reloadData })}
                                />
                                <Popconfirm title={`确认要删除该项目组信息吗？`} onConfirm={() => deleteInstitution(currentProject.oiUuid, reloadData)}>
                                    <Button title="删除当前项目组" icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                                </Popconfirm>
                            </ButtonGroup>

                            <ButtonGroup>
                                <Button
                                    icon={<IconPlusCircle />}
                                    title="添加项目组岗位成员"
                                    onClick={() =>
                                        openAddInstitutionMemberModal({
                                            institution: currentProject,
                                            institutionMembers: members,
                                            reloadData: loadInstitutionMembers,
                                        })
                                    }
                                />
                                <Button title="重新加载项目组岗位信息" icon={<IconRefresh />} onClick={loadInstitutionMembers}></Button>
                            </ButtonGroup>
                        </Space>
                    }
                >
                    <Descriptions size="small" bordered column={1} style={{ padding: 0 }} labelStyle={{ color: "#999", width: 120, textAlign: "left" }}>
                        <Descriptions.Item label="组名称">{currentProject.oiName}</Descriptions.Item>
                        <Descriptions.Item label="负责人">{currentProject.maInfo?.osName || "-"}</Descriptions.Item>
                        <Descriptions.Item label="管理人">{currentProject.asInfo?.osName || "-"}</Descriptions.Item>
                        <Descriptions.Item label="职能说明">{currentProject.oiDesc || "-"}</Descriptions.Item>
                        <Descriptions.Item label="创建信息">
                            {currentProject.crInfo?.name} - {currentProject.crInfo?.time ? formatUTCTime(currentProject.crInfo.time) : ""}
                        </Descriptions.Item>
                        <Descriptions.Item label="更新信息">
                            {currentProject.upInfo?.name} - {currentProject.upInfo?.time ? formatUTCTime(currentProject.upInfo.time) : ""}
                        </Descriptions.Item>
                    </Descriptions>

                    <div style={{ height: 10 }}></div>

                    <ProjectMembers loading={loading} members={members} reloadData={loadInstitutionMembers} />
                </SemiCard>
            </Col>
            <Col span={16}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{currentProject.oiName} - 下设机构列表</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    headerExtraContent={
                        <Space>
                            <ButtonGroup>
                                <Button icon={<TableOutlined />} theme={showType === "table" ? "solid" : "light"} onClick={() => (showType = "table")} />
                                {/* <Button title="当前项目组全景" icon={<ApartmentOutlined />} theme={showType === "tree" ? "solid" : "light"} onClick={() => (showType = "tree")} /> */}
                            </ButtonGroup>

                            <ButtonGroup>
                                <Button
                                    icon={<IconPlusCircle />}
                                    title="添加新项目组部门"
                                    onClick={() =>
                                        openAddProjectInstitutionDepartmentModal({
                                            institution: currentProject,
                                            reloadData: loadInstitutionDepartmentsWithMembers,
                                        })
                                    }
                                />
                                <Button icon={<IconRefresh />} onClick={loadInstitutionDepartmentsWithMembers}></Button>
                            </ButtonGroup>
                        </Space>
                    }
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                >
                    <DepartmentTable loading={dpLoading} institutions={departments} cardBodyHeight={cardBodyHeight} reloadData={loadInstitutionDepartmentsWithMembers} />
                </SemiCard>
            </Col>
        </Row>
    );
};

const DepartmentTable = ({ loading, institutions, cardBodyHeight, reloadData }) => {
    const { openEditProjectInstitutionDepartmentModal, openAddInstitutionMemberModal } = useHelperInstitution();
    const { deleteInstitution } = useDeleteInstitution();

    const renderDesc = (_, r, i) =>
        _ ? (
            <Tooltip title={_}>
                <EyeOutlined />
            </Tooltip>
        ) : (
            "-"
        );

    const renderPositions = (_, r, i) => (
        <ButtonGroup>
            <Button>{_?.length || 0}</Button>
            <Button
                icon={<IconPlusCircle />}
                onClick={() =>
                    openAddInstitutionMemberModal({
                        institution: r,
                        institutionMembers: r.members,
                        reloadData,
                    })
                }
            ></Button>
        </ButtonGroup>
    );

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Button theme="borderless" onClick={() => openEditProjectInstitutionDepartmentModal({ department: r, reloadData })}>
                编辑
            </Button>
            {r?.members?.length === 0 && (
                <Popconfirm
                    title="确认要删除该机构信息吗？"
                    okButtonProps={{ loading: false }}
                    onConfirm={async () => {
                        let res = await deleteInstitution(r.oiUuid);
                        if (res) {
                            message.success("成功删除机构信息");
                            reloadData();
                        }
                    }}
                >
                    <Button theme="borderless" style={{ color: "#f50" }}>
                        删除
                    </Button>
                </Popconfirm>
            )}
        </ButtonGroup>
    );

    const expandable = {
        expandedRowRender: (r) => <ProjectMembers members={r.members} reloadData={reloadData} />,
    };

    return (
        <Table loading={loading} bordered dataSource={institutions} rowKey={"id"} pagination={false} expandable={expandable} scroll={{ y: cardBodyHeight }}>
            <Table.Column title="序号" width={70} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="机构名称" dataIndex={"oiName"} />
            <Table.Column title="机构负责人" dataIndex={"maInfo"} width={140} render={(_, r, i) => _?.osName || "-"} />
            <Table.Column title="创建日期" dataIndex={"crInfo"} width={140} render={(_, r, i) => (_?.time ? formatUTCTime(_.time, "YYYY年MM月DD日") : "-")} />
            <Table.Column title="职责说明" dataIndex={"oiDesc"} align="center" width={100} render={renderDesc} />
            <Table.Column title="成员人数" dataIndex={"members"} align="center" width={100} render={renderPositions} />
            <Table.Column title="操作" width={140} render={renderOperate} />
        </Table>
    );
};

const ProjectMembers = ({ members, reloadData }) => {
    const { deleteInstitutionPosition } = useInstitutionDeletePosition();

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Popconfirm
                title="确认要删除该成员信息吗？"
                okButtonProps={{ loading: false }}
                onConfirm={async () => {
                    let res = await deleteInstitutionPosition(r.reUuid);
                    if (res) {
                        message.success("成功移除成员信息");
                        reloadData();
                    }
                }}
            >
                <Button theme="borderless" style={{ color: "#f50" }}>
                    移除
                </Button>
            </Popconfirm>
        </ButtonGroup>
    );

    return (
        <Table bordered dataSource={members} rowKey={"id"} size="small" pagination={false} style={{ margin: "10px 0" }}>
            <Table.Column title="序号" width={69} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="姓名" dataIndex={"omName"} />
            <Table.Column title="角色" dataIndex={"oimRemk"} />
            <Table.Column title="类型" dataIndex={"reType"} />
            <Table.Column title="操作" width={80} render={renderOperate} />
        </Table>
    );
};

export default ProjectPage;
